//怪物视图
import Global from "./store"
cc.Class({
    extends: cc.Component,
    properties: {
        P_monsterPrefab: {
            default: null,
            type: cc.Prefab,
            tooltip: "怪物节点预制"
        }
    },
    ctor() {
        this.monsterList = []
    },
    onLoad() {
        let aa = setInterval(() => {
            let monsterType = [10, 15, 18]
            let type = Global.random(0, 2)
            let index = Global.random(0, monsterType[type])
            this.creatMonster(type, index)
            if (this.monsterList.length > 10) {
                clearTimeout(aa)
            }
        }, 100);

        this.scheduleMonsterList = this.schedule(function () {
            this.monsterListSort()
            if (this.node.children.length == 0) {
                this.unschedule(this.scheduleMonsterList);
            }
        }, 0.5);

    },
    creatMonster(type, index) {
        //创建怪物
        let node = cc.instantiate(this.P_monsterPrefab); //怪物预制节点
        node.getComponent("monsterPrefab").setMonsterSpriteFrame(type, index) //type 怪物类型 0小怪物1中怪物2大怪物  //index 哪一个
        this.node.addChild(node) //插入怪物节点
        node.setPosition(Global.pathSizeData[0]) //设置怪物的出生点
        node.getComponent("monsterPrefab").action() //执行运动动画
        this.monsterList.push(node)
    },
    monsterListSort() {
        //怪物移动排序
        if (this.monsterList.length <= 1) {
            return
        }
        this.monsterList.sort((a, b) => {
            if (a.y - b.y > 0.1) {
                return -1;
            } else if (a.y == b.y) {
                return 0
            }
            return 1
        })
        for (let i = 0; i < this.monsterList.length; i++) {
            this.monsterList[i].zIndex = i

        }
    }
});